//
//  CircleProgressLayer.m
//  CircleProgress
//
//  Created by 邓岚锋 on 15/9/9.
//  Copyright (c) 2015年 邓岚锋. All rights reserved.
//

#import "CircleProgressLayer.h"

@implementation CircleProgressLayer{
    float radius; //半径
    float circleWidth;   //圆弧的宽度
}
/**
 * 绘制图形
 */
-(void)drawInContext:(CGContextRef)ctx{
    //绘制最外面白色的大圆
    radius = LAYER_BOUDS/2-20;
    circleWidth = 25;
    CGContextAddArc(ctx, self.bounds.size.width/2, self.bounds.size.height/2, radius, 0, M_PI*2, 0);
    CGContextSetStrokeColorWithColor(ctx, [UIColor whiteColor].CGColor);
    CGContextSetLineWidth(ctx, circleWidth);
    CGContextStrokePath(ctx);
    
    //绘制动态的小圆
    
    UIGraphicsBeginImageContext(CGSizeMake(LAYER_BOUDS, LAYER_BOUDS));
    CGContextRef imageCtx = UIGraphicsGetCurrentContext();
    CGContextAddArc(imageCtx, self.bounds.size.width/2, self.bounds.size.height/2, radius, M_PI_2-M_PI*2*self.progress, M_PI_2,  0);
    CGContextSetLineWidth(imageCtx, circleWidth);
    CGContextStrokePath(imageCtx);
    //创建图像掩码
    CGImageRef mask =  CGBitmapContextCreateImage(UIGraphicsGetCurrentContext());
    UIGraphicsEndImageContext();
    
    CGContextSaveGState(ctx);
    CGContextClipToMask(ctx, self.bounds, mask);
    CGImageRelease(mask);
    //绘制渐变
    
    CGColorSpaceRef  colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat components[12] = {
        0.0, 0.0, 1.0, 1.0,     // Start color - Blue
        1.0, 0.0, 1.0, 1.0,
        0.6, 0.8, 0.7, 1.0
    };
    CGGradientRef gradient =   CGGradientCreateWithColorComponents(colorSpace, components, NULL, 3);
    CGColorSpaceRelease(colorSpace);
    colorSpace = nil;
    
    CGPoint startPoint = CGPointMake(0, self.bounds.origin.y);
    CGPoint endPoint = CGPointMake(self.bounds.size.width, self.bounds.origin.y);
    CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint, 0);
    CGGradientRelease(gradient);
    gradient = nil;
    CGContextRestoreGState(ctx);
    
    CGContextAddEllipseInRect(ctx, CGRectMake((self.bounds.size.width-RECT_BOUDS)/2.0, (self.bounds.size.height-RECT_BOUDS)/2.0, RECT_BOUDS,RECT_BOUDS));
    CGContextSetFillColorWithColor(ctx, [UIColor whiteColor].CGColor);
    CGContextFillPath(ctx);
}
//增加新的progress属性
+(BOOL)needsDisplayForKey:(NSString *)key{
    return [key isEqualToString:@"progress"] ? YES :[super needsDisplayForKey:key];
}

@end
